package com.owulia.leetcode.num.stack;

public class BackspaceCompare {

    public boolean backspaceCompare(String s, String t) {
        char[] sChars = new char[s.length()];
        int sIndex = 0;
        char[] tChars = new char[t.length()];
        int tIndex = 0;
        sIndex = backspace(s, sChars, sIndex);
        tIndex = backspace(t, tChars, tIndex);
        if (sIndex != tIndex) {
            return false;
        }
        for (int i = 0; i < sIndex; i++) {
            if (sChars[i] != tChars[i]) {
                return false;
            }
        }
        return true;
    }

    private int backspace(String t, char[] tChars, int tIndex) {
        for (int i = 0; i < t.length(); i++) {
            char a = t.charAt(i);
            if (a == '#') {
                if (tIndex >= 0) {
                    tIndex--;
                }
            } else {
                tChars[tIndex] = a;
                tIndex++;
            }
        }
        return tIndex;
    }


    public boolean backspaceCompareAns(String s, String t) {
        int i = s.length() - 1;
        int sSkip = 0;
        int j = t.length() - 1;
        int tSkip = 0;
        while (i >= 0 || j >= 0) {
            while (i >= 0) {
                if (s.charAt(i) == '#') {
                    sSkip++;
                    i--;
                } else if (sSkip > 0) {
                    sSkip--;
                    i--;
                } else {
                    break;
                }
            }
            while (j >= 0) {
                if (t.charAt(j) == '#') {
                    tSkip++;
                    j--;
                } else if (tSkip > 0) {
                    tSkip--;
                    j--;
                } else {
                    break;
                }
            }
            if (i >= 0 && j >= 0) {
                if (s.charAt(i) != t.charAt(j)) {
                    return false;
                }
            } else if (i >= 0 || j >= 0) {
                return false;
            }
            i--;
            j--;
        }
        return true;
    }

}
